import userInfoApi from '@/api/basebiz/UserInfoApi'
import playAlarm from '@/utils/palyAlarm'
import { handleServiceI18n } from '@/service/i18n'
import { getParentsById, deepClone, handleAfsMaintText } from '@/utils/common'
import store from '..'

const baseConfig = {
  playConfigList: [],
  alarmConfigList: [],
  alarmAlert: [],
  speech: false,
  systemAlert: false,
  speechMode: 'CUSTOM'
}

/**
 * 告警配置和告警播报
 */
export default {
  state: {
    marqueeList: [],
    notifyList: [],
    alarmPlayRoute: '',
    alarmConfigData: deepClone(baseConfig),
    alarmList: [] // 告警列表
  },
  mutations: {
    SET_MARQUEEN_LIST(state, data) {
      state.marqueeList = data
    },
    ADD_MARQUEEN_LIST(state, data) {
      state.marqueeList.push(data)
      state.marqueeList
        .sort((a, b) => {
          return b.startTime - a.startTime
        })
        .sort((a, b) => {
          return a.alarmLevel - b.alarmLevel
        })
    },
    REMOVE_MARQUEEN_LIST(state, data) {
      state.marqueeList = state.marqueeList.filter(i => i.alarmId !== data.alarmId)
    },
    SET_NOTIFY_LIST(state) {
      const localList = localStorage.getItem('notifyList')
      const notifyList = JSON.parse(localList || '[]')
      state.notifyList = notifyList
    },
    ADD_NOTIFY_LIST(state, data) {
      state.notifyList.push(data)
      state.notifyList
        .sort((a, b) => {
          return b.startTime - a.startTime
        })
        .sort((a, b) => {
          return a.alarmLevel - b.alarmLevel
        })
    },
    CLEAR_NOTIFY_LIST(state) {
      state.notifyList = []
    },
    REMOVE_NOTIFY_LIST(state, data) {
      state.notifyList = state.notifyList.filter(i => i.alarmId !== data.alarmId)
    },
    RESET_NOTIFY_LIST(state, data) {
      if (!data.systemAlert) {
        state.notifyList = []
      } else {
        state.notifyList = state.notifyList.filter(i =>
          data.alarmAlert.includes(Number(i.alarmLevel))
        )
      }
    },
    SET_CONFIG(state, data) {
      state.alarmConfigData = data
    },
    SETALARM_ADD(state, data) {
      // 新增告警
      // console.log(data, 'SETALARM_ADD')
      // 不是所属区域权限内的告警不添加到列表
      if (
        !data.api &&
        data.regionId &&
        !store.getters.baseRegionList.some(i => i.regionId === data.regionId)
      ) { return }
      // 处理告警区域，站点状态，告警类型，告警等级信息
      if (data.regionId) {
        const trees = (
          getParentsById(store.getters.stationTree, data.regionId, 'key') || []
        ).reverse()
        if (trees.length > 0) {
          data.stationTextName = trees[trees.length - 1]['regionName'] || '' // 站点名称
          data.regionTextNames = trees
            .slice(0, trees.length - 1)
            .map(i => i.regionName)
            .join('/') // 区域名称
          data.stationStatusText =
            store.getters.dictMap['REGION_STATUS'][trees[trees.length - 1]['status']] // 站点状态
        } else {
          data.stationStatusText = ''
        }
      }
      data.alarmLevelText = store.getters.dictMap['ALARM_LEVEL'][data['alarmLevel']] // 告警等级
      data.alarmTypeText = store.getters.dictMap['ALARM_TYPE'][data['alarmType']] // 告警类型

      const index = state.alarmList.findIndex(i => i.alarmId === data.alarmId)
      data.description = handleAfsMaintText(data.description) // 设备检修告警特殊处理
      data.trigger = handleServiceI18n(data.trigger)
      data.description = handleServiceI18n(data.description)
      data.trigger = handleServiceI18n(data.trigger)
      data.description = handleServiceI18n(data.description)
      if (index > -1) {
        state.alarmList.splice(index, 1, data)
      } else {
        data.api ? state.alarmList.push(data) : state.alarmList.unshift(data)
        // console.log(state.alarmPlayRoute, data.alarmStatus)
        if (!data.api && data.alarmStatus !== 'CONFIRM') {
          const permission = store.getters.getAuthData('info:alarm')
          data.btns = [
            {
              key: 'view',
              label: 'VIEW',
              show: true
            },
            {
              key: 'confirm',
              show: permission.confirm && data.alarmStatus !== 'CONFIRM',
              label: 'CONFIRM'
            },
            {
              key: 'cancel',
              show: permission.cancel,
              label: 'CANCEL'
            }
          ]
          playAlarm.add(data) // 告警添加到播放列表
          this.commit('ADD_MARQUEEN_LIST', data)
        }
        if (data.alarmStatus === 'CONFIRM' || data.alarmStatus === 'CANCEL') {
          playAlarm.remove(data, true) // 从播放列表移除
          this.commit('REMOVE_MARQUEEN_LIST', data)
        }
      }
      state.alarmList
        .sort((a, b) => {
          return b.startTime - a.startTime
        })
        .sort((a, b) => {
          return a.alarmLevel - b.alarmLevel
        })
    },
    ALARM_REMOVE(state, data) {
      // 移除本地告警
      // console.log(data, 'ALARM_REMOVE')
      state.alarmList = state.alarmList.filter(i => i.alarmId !== data.alarmId)
      playAlarm.remove(data, true)
    },
    ALARM_PLAY_ROUTE(state, data) {
      // 设置告警播报路由
      state.alarmPlayRoute = data
    },
    CLEAR_ALARM(state) {
      state.alarmList = []
    },
    RESET_PLAY_LIST(state) {
      const speechList = deepClone(state.alarmList)
      speechList.forEach(item => {
        playAlarm.add(item)// 告警添加到播放列表
      })
    }
  },
  actions: {
    getConfigData({ commit, state }, reload) {
      // 获取配置的告警信息
      if ((state.alarmConfigData.userId && !reload) || !store.getters.dictList.ALARM_LEVEL) {
        return
      }
      userInfoApi
        .getAlarmNoticeConfig({
          userId: store.getters.getUserId
        })
        .then(res => {
          // console.log('getAlarmNoticeConfig', res)
          // console.log('store.getters.dictList', store.getters.dictList)
          const configData = res && res.data ? JSON.parse(res.data) : deepClone(baseConfig)
          const configList = store.getters.dictList.ALARM_LEVEL.map(i => {
            const level = Number(i.value)
            const curLevel = configData.alarmConfigList.find(j => level === Number(j.level))
            const number = curLevel ? curLevel.number : 4 - level
            const item = {
              speechType: curLevel ? curLevel.speechType : 'TIMES',
              alarmLabel: i.label,
              level: curLevel ? Number(curLevel.level) : level,
              number: number > 0 ? number : 1
            }
            return item
          })
          configData.alarmConfigList = configList
          // console.log('configData', configData)
          commit('SET_CONFIG', configData)
          commit('RESET_NOTIFY_LIST', configData)
          playAlarm.resetTime()
        })
        .catch(err => {
          console.log(err)
        })
    },
    playNext() {
      playAlarm.next()
    }
  },
  getters: {
    alarmConfigData: state => state.alarmConfigData, // 获取告警配置信息
    alarmList: state => state.alarmList, // 获取告警列表
    notifyList: state => state.notifyList,
    marqueeList: state => state.marqueeList,
    systemAlert: state => state.alarmConfigData.systemAlert
  }
}
